package com.atguigu.lease.web.admin.custom.converter;

import com.atguigu.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {
    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        Converter<String,T> converter = new Converter<String, T>() {
            @Override
            public T convert(String source) {
                //ItemType.values()  获取ItemType这个枚举中定义的所有常量值
                //targetType.getEnumConstants()   这是Class提供的API，表示获取 当前中的所有的枚举常量值 返回数组
                return Arrays.stream(targetType.getEnumConstants()).filter(t->source.equals(t.getCode()+"")).findFirst().orElseThrow(IllegalArgumentException::new);
            }
        };
        return converter;
    }
}
